﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Psm.Configuration;
using Psm.Container;
using System.Reflection;
using Psm.Session;
using Psm.Logging;

namespace Psm.Core
{
    public class PsmServer
    {
        private static ILogger logger = Repository.GetInstance<ILogger>();

        public PsmConfiguration Configuration { get; private set; }
        private ICollection<PsmHost> hosts = new List<PsmHost>();
        public ICollection<PsmHost> Hosts
        {
            get { return this.hosts; }
        }

        public void Start()
        {  
            //setup configuration
            this.Configuration = PsmConfiguration.GetConfiguration();

            //start each Server
            InitializeHosts();
        }

        private void InitializeHosts()
        {
            logger.Info("Starting Hosts...");
            foreach (HostConfiguration hostConfiguration in this.Configuration.Hosts)
            {
                try
                {
                    logger.Info("Starting [{0}] host", hostConfiguration.Name);
                    PsmHost host = new PsmHost(hostConfiguration);
                    this.hosts.Add(host);
                    host.Start();
                }
                catch (Exception ex)
                {
                    logger.Error("Failed to setup host [{0}]", hostConfiguration.Name);
                    logger.Exception(ex);
                }
            }
            logger.Info("All hosts started");
        }

        public void Stop()
        {
            foreach (PsmHost hostServer in hosts)
            {
                try
                {
                    logger.Info("Closing host [{0}]", hostServer.Configuration.Name);
                    hostServer.Stop();
                }
                catch (Exception ex)
                {
                    logger.Exception(ex);
                }
            }
        }
    }
}
